package com.cybertron.ironhide.search.controller;

import java.text.MessageFormat;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.cybertron.ironhide.search.common.Constants;
import com.cybertron.ironhide.search.service.ProductService;

@Controller
@RequestMapping("/rd")
public class RdController {

	@Autowired(required = false)
	private ProductService productService;

	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public String execute(@PathVariable("id") String id) {
		Map<String, String> rd = productService.selectRd(id);
		String urlTemplate = null;
		if (StringUtils.equals("amazon", rd.get("source"))) {
			urlTemplate = rd.get("targetUrl") + "?tag={0}";
		} else {
			urlTemplate = rd.get("targetUrl");
		}
		String url = MessageFormat.format(urlTemplate, Constants.ASSOCIATE_TAG);
		return "redirect:" + url;
	}
}
